import { defineStore } from 'pinia'
// 路由
import router from "@/router";
import base from '@/router/base'
import { clone } from "@/utils/util";
import { setDefaultRouter, routerFilterFunc } from "@/utils/handleRouter";
import permissionList from "@/utils/permission";

const useRouterStore = defineStore({
  id: 'router', // id必填，且需要唯一
  state: () => {
    return {
      permissionList: [] /** 所有路由 */,
      sidebarMenu: [] /** 导航菜单 */,
      currentMenu: "" /** 当前active导航菜单 */,
      isSidebarNavCollapse: false,  /* 导航菜单是否折叠 */
      crumbList: [],  /* 面包屑导航列表 */
    }
  },
  actions: {
    async fetchPermission() {
      // 处理动态路由
      const routes: any[] = routerFilterFunc(permissionList)
      // 不需要动态路由
      const mainContainer: any = clone(base).find(
        (v: any) => v.path === ""
      );
      let children: any[] = []
      children = mainContainer.children
      // 连接动态动态路由
      children = children.concat(routes)
      // 提交到vuex仓库管理 
      this.sidebarMenu = children
      mainContainer.children = children
      setDefaultRouter([mainContainer])
      let initalRoutes: any[] = router.options.routes
      // 添加路由 
      router.addRoute(mainContainer)
      this.permissionList = [...initalRoutes, ...base]
    }
  },
  getters: {
    GET_MENU: (state: any) => state.sidebarMenu, // 菜单
    GET_CURRENTMENU: (state: any) => state.currentMenu, // 当前菜单
    getCrumbList: (state: any) => state.crumbList, // 面包屑
    getIsSidebarNavCollapse: (state: any) => state.isSidebarNavCollapse, // 是否折叠
  }
})
export default useRouterStore